<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Middleware;

use App\Constants\ErrorCode;
use App\Exception\BussinessException;
use App\Utils\Jwt;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Utils\Context;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class AuthMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    protected $request;

    protected $response;

    /**
     * @Inject
     * @var Jwt
     */
    protected $jwt;

    public function __construct(ContainerInterface $container, RequestInterface $request, \Hyperf\HttpServer\Contract\ResponseInterface $response)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $token = $this->request->header('token', '');
        if (empty($token)) {
            throw new BussinessException(ErrorCode::PARAM_ERROR, 'token不能为空');
        }
        $checkRet = $this->jwt->checkToken($token);
        $isOk = $checkRet['is_ok'];
        $data = $checkRet['data'];
        if ($isOk) {
            Context::set('user_id', $data['user_id']);
            return $handler->handle($request);
        }
        return $this->response->json([
            'code' => $checkRet['code'],
            'msg' => ErrorCode::getMessage($checkRet['code']),
        ]);
    }
}
